﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

internal class TCP_Network
{
    #region        TCP服务端
    private Socket? socket;
    private Socket? clientSocket;
    public async Task Server(string IP,int Port)
    {
        //默认ip地址
        if (IP == "") IP = "127.0.0.1";
        //转换IP地址
        IPAddress IPaddress = IPAddress.Parse(IP);
        //添加端口
        IPEndPoint iPEnd = new IPEndPoint(IPaddress, Port);
        //使用套接字连接
        socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        //开始监听
        socket.Bind(iPEnd);
        //最多连接100个
        socket.Listen(100);
        while (true) 
        {
            //申请一个异步监听
            clientSocket = await socket.AcceptAsync();
            //读取数据
            _ = ReceiveData(clientSocket);
        }
    }

    public async Task ReceiveData(Socket _socket)
    {
        try
        {
            //初始化一个byte[]
            byte[] buffer = new byte[1024];
            while (true)
            {
                //异步接收数据
                int bytesRead = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer), SocketFlags.None);
                //将数据转换成string类型
                string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                //触发事件
                EventHub.RequestTab(content);
                await Task.Delay(1000);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public async Task ServerSend(string content)
    {
        try
        {
            //数据转换
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            //发送
            int index = await clientSocket.SendAsync(new ArraySegment<byte>(bytes), SocketFlags.None);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    #endregion

    #region        TCP客户端
    private Socket? ClientSocket;
    public async Task Client(string ip,int port)
    {
        try
        {
            //ip地址转换
            IPAddress iPadd = IPAddress.Parse(ip);
            //添加端口
            IPEndPoint EndPost = new IPEndPoint(iPadd, port);
            //创建一个套接字
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //连接
            await ClientSocket.ConnectAsync(EndPost);
            //接收数据
            await ReceiveData(ClientSocket);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public async Task ClientSend(string content)
    {
        try
        {
            //数据转换
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            //发送
            int index = await ClientSocket.SendAsync(new ArraySegment<byte>(bytes), SocketFlags.None);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        
    }

    public void Dispose() 
    {
        if (ClientSocket != null)
        {
            ClientSocket.Close();
            ClientSocket.Dispose();
        }
    }
    #endregion

    
}
